package com.wenda.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wenda.admin.bean.*;
import com.wenda.admin.constant.UserTypeEnum;
import com.wenda.admin.constant.YesNoEnum;
import com.wenda.admin.mapper.*;
import com.wenda.admin.utils.DateUtil;
import com.wenda.admin.vo.BizCode;
import com.wenda.admin.vo.LoginVO;
import com.wenda.admin.vo.QrCodeVO;
import com.wenda.admin.vo.Resp;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("api")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Api {
    private final AccountMapper accountMapper;
    private final StudentMapper studentMapper;
    private final TeacherMapper teacherMapper;
    private final SecurityPersonnelMapper securityMapper;
    private final EntryRecordMapper entryRecordMapper;


    /**
     * 生成二维码
     *
     * @return
     */
    @RequestMapping("createQrCode")
    @ResponseBody
    public Resp createQrCode(HttpSession session) {
        LoginVO account = (LoginVO) session.getAttribute("userKey");
        if (account == null) {
            return Resp.error("请重新登录之后再刷新出入码", null);
        }

        QrCodeVO qrCodeVO = new QrCodeVO();

        UserTypeEnum userType = UserTypeEnum.toEnum(account.getUserType());
        switch (userType){
            case STUDENT:
                qrCodeVO.setTn(studentMapper.selectById(account.getInfoId()).getTemperatureStatus());
                break;
            case TEACHER:
                qrCodeVO.setTn(teacherMapper.selectById(account.getInfoId()).getTemperatureStatus());
                break;
        }

        qrCodeVO.setAccountId(account.getAccountId());
        qrCodeVO.setTimeStamp(String.valueOf(System.currentTimeMillis()));
        qrCodeVO.setName(account.getName());

        return Resp.success(qrCodeVO);
    }

    /**
     * 扫码
     *
     * @param session
     * @return
     */
    @RequestMapping("scan")
    @ResponseBody
    public Resp getQrCode( HttpSession session, String code) {
        if(StringUtils.isBlank(code)){
            return Resp.error(BizCode.BAD_CODE);
        }
        String[] split = code.split(",");
        if(split.length != 2){
            return Resp.error(BizCode.BAD_CODE);
        }
        String accountId = split[0];
        Account account = accountMapper.selectById(accountId);
        if(account == null){
            return Resp.error(BizCode.BAD_CODE);
        }
        return Resp.success(account);
    }


    /**
     * 查询出入记录
     *
     * @param session
     * @return
     */
    @RequestMapping("recordHis")
    @ResponseBody
    public Resp record(HttpSession session) {
        LoginVO account = (LoginVO) session.getAttribute("userKey");
        List<EntryRecord> entryRecords = entryRecordMapper.selectList(new LambdaQueryWrapper<EntryRecord>().eq(EntryRecord::getUserId, account.getInfoId()).orderByDesc(EntryRecord::getEntryTime));
        if(entryRecords != null && entryRecords.size() > 0){
            for(EntryRecord temp:entryRecords){
                temp.setEntryTimeStr(DateUtil.format(temp.getEntryTime()));
            }
        }
        return Resp.success(entryRecords);
    }


    /**
     * 出入记录
     *
     * @param session
     * @return
     */
    @RequestMapping("record")
    @ResponseBody
    public Resp record(HttpSession session,String accountId,String entryType,Float temperature,String remark) {
        if(StringUtils.isBlank(accountId) || temperature == null || temperature < 30 || temperature > 50){
            return Resp.error("错误的温度，请校验后重新录入", null);
        }
        LoginVO operator = (LoginVO) session.getAttribute("userKey");
        SecurityPersonnel securityPersonnel = securityMapper.selectById(operator.getInfoId());

        Account account = accountMapper.selectById(accountId);

        // 出入记录
        EntryRecord record = new EntryRecord();
        record.setUserType(account.getUserType());
        record.setUserId(account.getInfoId());
        record.setName(account.getName());
        record.setMobile(account.getMobile());
        record.setTemperature(temperature);
        record.setEntryTime(new Date());
        record.setRemark(remark);
        record.setEntryType(entryType);
        record.setOperatorName(operator.getName());
        record.setOperatorMobile(operator.getMobile());
        record.setGateName(securityPersonnel.getGateName());
        entryRecordMapper.insert(record);


        if (temperature > 37.3){
            // 温度异常状态更新
            UserTypeEnum userType = UserTypeEnum.toEnum(account.getUserType());
            switch (userType){
                case STUDENT:
                    Student student = new Student();
                    student.setId(account.getInfoId());
                    student.setTemperatureStatus(YesNoEnum.NO.getId());
                    student.setLastEntryTime(new Date());
                    studentMapper.updateById(student);
                    break;
                case TEACHER:
                    Teacher teacher = new Teacher();
                    teacher.setId(account.getInfoId());
                    teacher.setTemperatureStatus(YesNoEnum.NO.getId());
                    teacher.setLastEntryTime(new Date());
                    teacherMapper.updateById(teacher);
                    break;
            }
        }
        return Resp.success("登记成功",null);
    }

}
